package com.mrd.gtimp.base.service;

import com.mrd.base.BaseBiz;
import com.mrd.gtimp.base.entity.Role;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.repository.UserDao;
import com.mrd.spring.repository.BaseRepository;
import com.mrd.util.LoginUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

import javax.annotation.Resource;


/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author qiul
 */
@Service
public class UserBiz extends BaseBiz<User> {
    @Resource
    private UserDao userDao;
    @Resource
    private CompanyBiz companyBiz;

    @Resource
    // 该处指定注入BiBaseRepository的dao对象
    @Qualifier("userDao")
    public void setBaseRepository(BaseRepository<User, String> baseRepository) {
        super.baseRepository = baseRepository;
    }

    /**
     * 通过账号查找用户
     *
     * @param account 账号
     * @return 用户
     */
    public User findByAccount(String account) {
        if (StringUtils.isEmpty(account)) {
            return null;
        }
        User user = userDao.findByAccountAndIsabledAndState(account, String.valueOf(0), String.valueOf(0));
//        try {
//            Company company = companyBiz.findEntityById(user.getCompany().getId());
//        } catch (QueryException e) {
//            e.printStackTrace();
//        }
        //防止无法获取到session的错误，预先加载role
        user.getRoles();
        //防止无法获取到session的错误，预先加载model
        user.getModules();
        return user;
    }

    /**
     * 检查用户是否包含指定角色roleNames
     * @param roleNames 角色名称
     * @return 检查结果 true or false
     * add by dengdc on 2017-11-17
     */
    public boolean currentUserContainRoles(String... roleNames){
        boolean checkFlag = true;
        List<Role> roleList = LoginUtil.getLoginUser().getRoles();
        out : for (String roleName : roleNames) {
            for (Role role : roleList) {
                if(roleName.equals(role.getName())){
                    continue out;
                }
            }
            //任何一个角色名没匹配到，则检查不通过
            checkFlag = false;
            break;
        }
        return checkFlag;
    }

    /**
     * 检查用户是否包含指定角色roleNames 中的其中一个
     * @param roleNames 角色名称
     * @return 检查结果 true or false
     * add by dengdc on 2017-11-17
     */
    public boolean currentUserContainOneOfRoles(String... roleNames){
        List<Role> roleList = LoginUtil.getLoginUser().getRoles();
        for (String roleName : roleNames) {
            for (Role role : roleList) {
                if(role.getName().contains(roleName)){
                    return  true;
                }
            }
        }
        return false;
    }
}
